from django.shortcuts import render

# Create your views here.
from rest_framework.generics import GenericAPIView, ListAPIView
from rest_framework.response import Response
from rest_framework.filters import OrderingFilter
from drf_haystack.viewsets import HaystackViewSet

from goods.models import GoodsCategory, SKU
from goods.serializer import ChannelSerializer, CategorySerializer, SKUSerializer, SKUIndexSerializer


class CategoryView(GenericAPIView):
    """
    商品列表页面的面包屑
    """
    queryset = GoodsCategory.objects.all()

    def get(self, request, pk=None):
        ret = dict(
            cat1="",
            cat2="",
            cat3=""
        )
        category = self.get_object()
        # 当前级别为第一级别, 则其父目录为null(该数据库为自相关)
        if category.parent is None:
            ret['cat1'] = ChannelSerializer(category.goodschannel_set.all()[0]).data
        # 当前级别为三级级别，　其子对象没有任何的数据
        elif category.goodschannel_set.count() == 0:
            ret['cat3'] = CategorySerializer(category).data
            cat2 = category.parent
            ret['cat2'] = CategorySerializer(cat2).data
            ret['cat1'] = ChannelSerializer(cat2.parent.goodschannel_set.all()[0]).data

        else:
            # 当前类别为二级
            ret['cat2'] = CategorySerializer(category).data
            ret['cat1'] = ChannelSerializer(category.parent.goodschannel_set.all()[0]).data

        return Response(ret)


class SKUListView(ListAPIView):
    # 列出所以第三类商品的详细ＳＫＵ内容,传入参数是ｐｋ,要使Sku数据库中的字段category_id ==pk
    serializer_class = SKUSerializer

    filter_backends = (OrderingFilter,)
    ordering_fields = ('create_time', 'price', 'sales')

    def get_queryset(self):
        # 设置当前列表中的商品sku信息只能是上架和当前分类
        # self.kwargs　指代获取路由中的正则参数的值，drf内部的APIView视图类中声明的
        category_id = self.kwargs["category_id"]
        return SKU.objects.filter(category_id=category_id, is_launched=True)

class SKUSearchViewSet(HaystackViewSet):
    """
    SKU搜索  必须使用视图集
    """
    # 索引类模型[这个属性在我们安装了和注册了 haystack子应用，自动提供了 ]
    index_models = [SKU]
    serializer_class = SKUIndexSerializer
